import {XHttp} from 'react-native-easy-app';
import DeviceInfo from 'react-native-device-info';
import { Platform } from "react-native";
import { Api } from './Api';
import {fixMasterIp} from "../logic/TestDataGenerate";
import DataCenter from '../logic/DataCenter';
import { ACK_Type } from '../logic/LogicConstant';
import ProtocolSignUtils from '../common/Utils/ProtocolSignUtils';
import Config from 'react-native-config';

export async function register(ip, serverIp, code, info) {
    let HttpReq = XHttp("mqttmonitor");
    let reqUrl = Config.HTTP_PROTOCOL + "://" + serverIp + ":" + Config.HTTP_PORT + "/tiot/mqtt/registDevice";
    let req = {
        "gateId": code,
        "gateIp": ip,
        "serverId":"",//serverId传空,不签名
        "timeStamp": ""+Date.now(),
        "sign": "",
        "info": info,
    }

    return HttpReq.url(reqUrl).param({
        "id": ""+Date.now(),
        "version": "1.0",
        "sys":{
            "ack": ACK_Type.ACK
        },
        "params":req,
        "method": "thing.sub.register"
      }).execute('post').then(({success, json, msg})=>{
        const {data, code, message} = json;
        console.log("data:",data);
        return {success: success && code===200, data, message};
    }).catch(e=>{
        return {success: false, message:"网络异常"};
    });
}

export async function getAppVersion() {
    let HttpReq = XHttp("mqttmonitor");
    let reqUrl = Config.HTTP_PROTOCOL + "://" + DataCenter.serverIp + ":" + Config.HTTP_PORT + "/tiot/update/updateVersion";
    return HttpReq.url(reqUrl).param({
            systemId: 20,
            gateId: DataCenter.gateId,
            ver: DeviceInfo.getBuildNumber(),
            versionName: DeviceInfo.getVersion(),
        }).execute('post').then(({success, json, msg})=>{
        const {data, status, message} = json;
        let md_data = data||{};
        if(md_data && md_data.url && md_data.url.startsWith('http')) {
            md_data.url = md_data.url;
        } else {
            md_data.url = Config.HTTP_PROTOCOL + "://" + DataCenter.serverIp + ":" + Config.HTTP_PORT + md_data.url;
        }
        return {success: success && status===0, data: md_data, message};
    }).catch(e=>{
        return {success: false, message:"网络异常"};
    });
}